<template>
  <div class="min-h-screen bg-gray-50 flex flex-col justify-center py-6 sm:py-12 px-4 sm:px-6 lg:px-8">
    <div class="sm:mx-auto sm:w-full sm:max-w-md">
      <!-- Logo -->
      <div class="flex justify-center">
        <RandomLogo />
      </div>
      <h2 class="mt-4 sm:mt-6 text-center text-2xl sm:text-3xl font-extrabold text-gray-900">
        馒头AI助手
      </h2>
      <p class="mt-2 text-center text-sm text-gray-600">
        登录您的账户开始使用
      </p>
    </div>

    <div class="mt-6 sm:mt-8 sm:mx-auto sm:w-full sm:max-w-md">
      <div class="bg-white py-6 sm:py-8 px-4 shadow sm:rounded-lg sm:px-10">
        <!-- 登录表单 -->
        <form class="space-y-6" @submit.prevent="handleLogin">
          <div>
            <label for="username" class="block text-sm font-medium text-gray-700">
              用户名
            </label>
            <div class="mt-1">
              <input
                id="username"
                name="username"
                type="text"
                required
                v-model="form.username"
                maxlength="12"
                minlength="4"
                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                placeholder="请输入用户名"
              />
            </div>
          </div>

          <div>
            <label for="password" class="block text-sm font-medium text-gray-700">
              密码
            </label>
            <div class="mt-1">
              <input
                id="password"
                name="password"
                type="password"
                required
                v-model="form.password"
                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                placeholder="请输入密码"
              />
            </div>
          </div>

          <!-- 验证码 -->
          <div>
            <label for="captcha" class="block text-sm font-medium text-gray-700">
              验证码
            </label>
            <div class="mt-1 flex space-x-2">
              <input
                id="captcha"
                name="captcha"
                type="text"
                required
                v-model="form.captcha"
                class="flex-1 appearance-none block px-3 py-2 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                placeholder="请输入验证码"
              />
              <div class="relative">
                <img
                  v-if="captchaUrl"
                  :src="captchaUrl"
                  @click="refreshCaptcha"
                  class="h-10 w-24 border border-gray-300 rounded cursor-pointer"
                  alt="验证码"
                />
                <div 
                  v-else-if="captchaLoading"
                  class="h-10 w-24 border border-gray-300 rounded flex items-center justify-center bg-gray-100"
                >
                  <span class="text-xs text-gray-500">加载中...</span>
                </div>
                <div 
                  v-else
                  class="h-10 w-24 border border-red-300 rounded flex items-center justify-center bg-red-50 cursor-pointer"
                  @click="refreshCaptcha"
                >
                  <span class="text-xs text-red-500">点击重试</span>
                </div>
              </div>
            </div>
            <!-- 验证码错误提示 -->
            <div v-if="captchaError" class="mt-1 text-sm text-red-600">
              {{ captchaError }}
            </div>
            
            <!-- 调试信息 - 仅在有错误且有调试URL时显示 -->
            <div v-if="captchaError && debugCaptchaUrl && !captchaUrl" class="mt-2 p-2 bg-blue-50 border border-blue-200 rounded text-xs">
              <p class="text-blue-600 mb-1">调试：直接访问验证码链接</p>
              <a :href="debugCaptchaUrl" target="_blank" class="text-blue-500 hover:text-blue-700 underline break-all">
                在新窗口打开验证码
              </a>
            </div>
          </div>

          <div>
            <button
              type="submit"
              :disabled="loading"
              class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
            >
              <span v-if="loading">登录中...</span>
              <span v-else>登录</span>
            </button>
          </div>

          <div class="text-center">
            <router-link
              to="/register"
              class="text-sm text-blue-600 hover:text-blue-500"
            >
              还没有账户？立即注册
            </router-link>
          </div>
        </form>

        <!-- 二次元气泡弹窗 -->
        <transition name="bubble-fade">
          <div v-if="showUserNotExistBubble" class="bubble-dialog-anime">
            <div class="bubble-content">
              <span>该用户不存在，请先注册账户！</span>
              <div class="mt-2 flex gap-2 justify-end">
                <button @click="goRegister" class="bubble-btn">去注册</button>
                <button @click="showUserNotExistBubble = false" class="bubble-btn">关闭</button>
              </div>
            </div>
          </div>
        </transition>

        <!-- 错误提示 -->
        <div v-if="error" class="mt-4 p-3 bg-red-50 border border-red-200 rounded-md">
          <p class="text-sm text-red-600">{{ error }}</p>
        </div>

        <!-- 连接状态提示 -->
        <div v-if="!backendConnected" class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-md">
          <p class="text-sm text-yellow-700">
            ⚠️ 无法连接到后端服务器，请确保SpringBoot服务在http://localhost:9901正常运行
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { getCaptcha, login, getUserName } from '../api/index'
import RandomLogo from '../components/RandomLogo.vue'

const router = useRouter()
const authStore = useAuthStore()

const form = ref({
  username: '',
  password: '',
  captcha: ''
})

const captchaUrl = ref('')
const captchaLoading = ref(false)
const captchaError = ref('')
const loading = ref(false)
const error = ref('')
const backendConnected = ref(true)
const debugCaptchaUrl = ref('')
const showUserNotExistBubble = ref(false)

// 获取验证码
const refreshCaptcha = async () => {
  captchaLoading.value = true
  captchaError.value = ''
  captchaUrl.value = ''
  backendConnected.value = true
  
  try {
    console.log('开始获取验证码...')
    const response = await getCaptcha()
    console.log('验证码API响应:', response)
    
    if (response.code == 200) {
      console.log('验证码URL:', response.data)
      
      // 保存调试URL  
      debugCaptchaUrl.value = response.data
      
      // 直接使用返回的URL，不进行复杂的加载测试
      captchaUrl.value = response.data
      captchaError.value = ''
      backendConnected.value = true
      
      console.log('验证码URL设置完成:', captchaUrl.value)
    } else {
      captchaError.value = response.message || '获取验证码失败'
      console.error('验证码API返回错误:', response)
    }
  } catch (err) {
    console.error('获取验证码失败:', err)
    captchaError.value = '无法获取验证码，请检查网络连接'
    backendConnected.value = false
    
    // 如果是网络错误，提供重试机制
    if (err.code === 'ECONNREFUSED' || err.message?.includes('Network Error')) {
      captchaError.value = '后端服务连接失败，请确保SpringBoot服务正在运行'
    }
  } finally {
    captchaLoading.value = false
  }
}

// 登录处理
const handleLogin = async () => {
  if (!form.value.username || !form.value.password || !form.value.captcha) {
    error.value = '请填写完整信息'
    return
  }

  if (!backendConnected.value) {
    error.value = '无法连接到后端服务器，请稍后重试'
    return
  }

  loading.value = true
  error.value = ''

  try {
    // 首先检查用户是否存在
    const userExists = await checkUserExists(form.value.username)
    if (!userExists) {
      showUserNotExistBubble.value = true
      loading.value = false
      return
    }

    // 用户存在，继续登录流程
    const response = await login({
      username: form.value.username,
      password: form.value.password,
      captcha: form.value.captcha
    })

    if (response.code == 200) {
      authStore.login(response.data.jwt, response.data.username)
      // 根据屏幕大小跳转到对应页面
      if (window.innerWidth <= 768) {
        router.push('/mobile-home')
      } else {
        router.push('/home')
      }
    } else {
      error.value = response.message || '登录失败'
      refreshCaptcha()
    }
  } catch (err) {
    error.value = err.response?.data?.message || '登录失败，请稍后重试'
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

// 检查用户是否存在
const checkUserExists = async (username) => {
  try {
    const response = await getUserName(username)
    // 只看data字段
    return !!response.data
  } catch (err) {
    console.error('检查用户存在性失败:', err)
    return true // 查询失败时允许继续登录
  }
}

const goRegister = () => {
  showUserNotExistBubble.value = false
  router.push('/register')
}

onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.bubble-dialog-anime {
  position: fixed;
  top: 20%;
  left: 50%;
  transform: translate(-50%, 0);
  background: linear-gradient(135deg, #f3e7ff 0%, #e3f0ff 100%);
  border-radius: 1.5rem;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.2);
  padding: 2rem 2.5rem;
  z-index: 1000;
  animation: bubble-pop 0.4s cubic-bezier(.68,-0.55,.27,1.55);
}
.bubble-content {
  font-size: 1.1rem;
  color: #6b21a8;
  font-family: 'ZCOOL KuaiLe', 'Comic Sans MS', cursive, sans-serif;
}
.bubble-btn {
  background: #a78bfa;
  color: #fff;
  border: none;
  border-radius: 999px;
  padding: 0.4rem 1.2rem;
  font-size: 1rem;
  margin-left: 0.5rem;
  cursor: pointer;
  transition: background 0.2s;
}
.bubble-btn:hover {
  background: #7c3aed;
}
@keyframes bubble-pop {
  0% { transform: scale(0.7) translate(-50%, 0); opacity: 0; }
  100% { transform: scale(1) translate(-50%, 0); opacity: 1; }
}
.bubble-fade-enter-active, .bubble-fade-leave-active {
  transition: opacity 0.3s;
}
.bubble-fade-enter-from, .bubble-fade-leave-to {
  opacity: 0;
}
</style> 